import React, {useEffect ,useState,forwardRef,useImperativeHandle} from 'react'
import UserOrg from '@/api/userorg'
import { Modal,Tree, message} from 'antd'
import { TreeNode } from 'rc-tree'
import {
  TeamOutlined,
  UserOutlined
} from '@ant-design/icons';
import './index.less'
const ChooseUser = (props,refs) => {
  // const [loading, setLoading] = useState<boolean>(false)
  //显示隐藏弹窗
  const [isModalVisible, setIsModalVisible] = useState(false);
  
   //显示隐藏树
   const [isTreeVisible, setIsTreeVisible] = useState(false);
  //菜单树
  const [treeData,setTreeData] = useState<any[]>([]);

  const handledata = (data)=>{

    data.map((e,i)=>{
      data[i]['key'] = e['deptId']?e['deptId']:e['corpId'];
      let deptVo = e['deptVo']?e['deptVo']:[]
      let children = deptVo.concat(e['children']);
      let title = e['corpName']||e['deptName']
      let deptShortName = e['corpShortName']||e['deptShortName']
      let type = e['corpName']?2:1
      let sub = e['supCorpId']||e['supDept']
      data[i]['title'] = title;
      data[i]['type'] = type;
      data[i]['sub'] = sub;
      data[i]['deptShortName'] = deptShortName;
      if(children.length==0){
        let obj = Object.assign(e,{});
        delete obj['children'];
        delete obj['deptVo'];
        data[i] = obj;
      }else{
        let childrennew = handledata(children);
        data[i]['children'] = childrennew;
      }
    })
    return data;
  }
  //获取菜单树
  const getTree = ()=>{
    UserOrg.getUserTree().then((res)=>{
      let data = res.data;
      data = handledata(data);
      setTreeData(data);
      setIsTreeVisible(true);
    });
  }
  //选中
  const [checkedAr,setCheckedArr] = useState([]);

  //选中
  const [checkedObjArr,setCheckedObjArr] = useState([]);
  //  let fieldNames = { title: 'menuname', key: 'menuid', children: 'children' };
  // const handledata = (data)=>{
  //   data.map((e,i)=>{
  //     if(e['children']&&e['children'].length>0){
  //       e['children'] = handledata(e['children']);
  //     }
  //   })

  //   return data;
  // }
  useEffect(()=>{
    getTree();
  },[])
  useImperativeHandle(refs, () => ({
    init: (id) => {
      showModal();
    }
  }))
 
  //显示弹窗
  const showModal = () => {
    setIsModalVisible(true);
    setIsTreeVisible(true);
  };
  //确定
  const handleOk = () => {
    if(checkedAr.length===0){
      message.error('最少选择一个');
      return;
    }
    handleCancel();
  };
  //取消
  const handleCancel = () => {
    setIsModalVisible(false);
    setIsTreeVisible(false);
    
    props.callback&&checkedObjArr.length>0&&props.callback(checkedObjArr);
    setCheckedArr([]);
    setCheckedObjArr([]);
  };
  const onSelect = (selectedKeys: React.Key[], info: any) => {
    if(selectedKeys.length>0){
      setCheckedArr(selectedKeys);
      setCheckedObjArr([{
          'id':info['node']['key'],
          'name':info['node']['title'],
      }])
    }
  };

  // const onCheck = (checkedKeys, info: any) => {
  //   console.log('onCheck', checkedKeys, info);
  // };
  const renderTree = (data)=>{
    let treeNodeArr = [];
    data.map((e)=>{
      let users = e['qyWeiXinVo']?e['qyWeiXinVo']:[];
      let children = e['children']?e['children']:[];
      users.map((e,i)=>{
        users[i]['type'] = 'user';
      })
      children = children.concat(users);
      if(e['type']=='user'){
        treeNodeArr.push(<TreeNode className="fe_tree_user" icon={<UserOutlined />} selectable={true} key={e['staffId']} title={e['staffName']}></TreeNode>)
      }else{
        treeNodeArr.push(<TreeNode icon={<TeamOutlined />} selectable={false} title={<div className="orgItem">
        <div className='orgname'>
          {e['title']}
        </div>
        </div>
        } 
        key={e['key']}>
        {
          children&&renderTree(children)
        }
      </TreeNode>);
      }
      return 1
    })
    return treeNodeArr;
  }
  return <Modal 
    title="选择人员" 
    visible={isModalVisible} 
    onOk={handleOk} 
    onCancel={handleCancel}
    width={600}
    centered={true}
    maskClosable={false}
    bodyStyle={{
      height: window.innerHeight - 250,
      overflowY:'auto'
    }}
    className="left_tree"
    >
      {
        isTreeVisible&&<Tree
        defaultExpandAll={true}
        onSelect={onSelect}
        selectedKeys={checkedAr}
        showIcon={true}
      >
        {
          renderTree(treeData)
        }
      </Tree>
      }
</Modal>
}

const ChooseUserCom = forwardRef(ChooseUser);
export default ChooseUserCom